package com.zhuiyun.project.api.frontuser.controller;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.json.JSONObject;
import com.zhuiyun.project.annotation.OptLog;
import com.zhuiyun.project.api.frontuser.entity.EmailDto;
import com.zhuiyun.project.api.frontuser.entity.FrontUser;
import com.zhuiyun.project.api.tag.entity.Tag;
import com.zhuiyun.project.api.frontuser.model.FrontUserModel;
import com.zhuiyun.project.api.frontuser.service.FrontUserService;
import com.zhuiyun.project.api.frontuser.utils.MailUtil;
import com.zhuiyun.project.common.errorCode.CommonException;
import com.zhuiyun.project.common.response.CommonResult;
import com.zhuiyun.project.utils.RedisCache;
import com.zhuiyun.project.utils.VerifyCodeUtils;
import com.zhuiyun.project.utils.constants.CommonConstants;
import com.zhuiyun.project.utils.pageUtil.PageRequest;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import static java.util.concurrent.TimeUnit.SECONDS;
import static com.zhuiyun.project.utils.MailUtils.sendMail;

/**
 * @ClassName FrontUserController
 * @Description TODO 前端用户管理模块
 * @Author XMY
 * @Date 2023/12/11 8:57
 **/
@RestController
@RequestMapping("frontUser")
@Api(tags = "前端用户管理")
public class FrontUserController {
    @Autowired
    private FrontUserService frontUserService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private MailUtil mailUtil;
    @Autowired
    private RedisCache redisCache;
    private String randomNumber;

    /**
    * @Author 雅俗共赏
    * @Description
    * @Date 2024/3/19 8:39
    * @Return com.zhuiyun.project.common.response.CommonResult
    * 跳转前token验证
    */
    @GetMapping("/JumpVerification")
    @ApiOperation(value = "token验证")
    public CommonResult JumpVerification(FrontUserModel frontUserModel){
        String jsonstr = stringRedisTemplate.opsForValue().get(frontUserModel.getToken());
        if (jsonstr == null || jsonstr.equals("")) {
            return CommonResult.error(404,"用户验证失败,请重新登录");
        } else {
            return CommonResult.ok("验证通过");
        }
    }

    /**
    * @Author 雅俗共赏
    * @Description
    * @Date 2024/3/19 8:38
    * @Return com.zhuiyun.project.common.response.CommonResult
    * 邮箱发送验证码
    */
    @PostMapping("/generateEmailCode1")
    @ResponseBody
    public CommonResult generateEmailCode1(@RequestBody FrontUser frontUser){
        if (frontUser.getEmail() != null){
            EmailDto emailDto = new EmailDto();
            emailDto.setRecipient(frontUser.getEmail());//接收者
            emailDto.setSubject("诗音账户安全码:");//标题
            //验证码
            randomNumber = RandomUtil.randomNumbers(5);
            //内容主体
            emailDto.setContent(randomNumber+"当前时间为：" + new Date());
            mailUtil.sendSimpleMail(emailDto);
            return CommonResult.ok("发送成功");
        }
        return CommonResult.ok("发送失败！");
    }
    /**
     * @Author XMY
     * @Description 生成邮箱验证码
     * @Date 2023/12/13 10:57
     * @Return
     * @param frontUser
     */
    @ApiOperation(value = "生成邮箱验证码的方法")
    @PostMapping("/generateEmailCode")
    public CommonResult generateEmailCode(@RequestBody FrontUser frontUser) {
        String email = frontUser.getEmail();
        // 生成随机字符串
        String verifyCode = VerifyCodeUtils.generateVerifyCode(6);
        // 存储到 Redis 中，时效120s
        redisCache.setCacheObject(CommonConstants.CACHE_EMAIL_CODE +verifyCode , verifyCode, 120, SECONDS);
        redisCache.setCacheObject(CommonConstants.CACHE_EMAIL + email, email, 120, SECONDS);
        // 发送邮件
        try {
            String subject = "验证码";
            String content = "您的验证码为：" + verifyCode;
            sendMail(email, subject, content);
            return CommonResult.ok("验证码已发送到邮箱，请注意查收");
        } catch (Exception e) {
            e.printStackTrace();
            return CommonResult.error("验证码发送失败");
        }
    }
    /**
     * @Author XMY
     * @Description 根据id用户信息，绑定邮箱
     * @Date 2023/12/12 8:28
     * @Return
     */
    @GetMapping("/judgeCode")
    @ApiOperation(value = "绑定邮箱")
    public CommonResult judgeCode(FrontUserModel frontUserModel) throws CommonException {
        int userId;
        String jsonstr = stringRedisTemplate.opsForValue().get(frontUserModel.getToken());
        if (jsonstr == null || jsonstr.equals("")) {
            return CommonResult.error(404,"用户信息失效,请重新登录");
        } else {
            // 使用JSONObject解析ISON字符串
            JSONObject json0bject = new JSONObject(jsonstr);
            // 获取id字段的值
            userId = json0bject.getInt("id");
        }
        if(frontUserModel.getCode().equals(randomNumber)){
            Boolean jg=frontUserService.updateEmail(frontUserModel.getEmail(),userId);
            if(jg){
                return CommonResult.ok("绑定成功");
            }else {
                return CommonResult.error(500,"绑定失败");
            }
        }else {
            return CommonResult.error(500,"验证码有误");
        }
    }
    /**
     * @param frontUserModel
     * @Author XMY
     * @Description 修改用户信息
     * @Date 2023/12/11 16:11
     * @Return
     */
    @PutMapping("updateFrontUser")
    @ApiOperation(value = "修改前端用户信息")
    public CommonResult updateFrontUser(@RequestBody FrontUserModel frontUserModel) throws CommonException {
        String jsonstr = stringRedisTemplate.opsForValue().get(frontUserModel.getToken());
        if (jsonstr == null || jsonstr.equals("")) {
            return CommonResult.error(404,"用户信息失效,请重新登录");
        }else {
            return CommonResult.ok(frontUserService.updateFrontUser(frontUserModel));
        }
    }
    /**
     * @param frontUserModel
     * @Author LYX
     * @Description 用户修改密码
     * @Date 2024/3/20 16:11
     * @Return
     */
    @PutMapping("/changePassword")
    @ApiOperation(value = "前端用户修改密码")
    public CommonResult changePassword(@RequestBody FrontUserModel frontUserModel){
        String jsons = stringRedisTemplate.opsForValue().get(frontUserModel.getToken());
        if (jsons == null || jsons.isEmpty()) {
            return CommonResult.error(404,"用户信息失效,请重新登录");
        }else {
            JSONObject json0bject = new JSONObject(jsons);
            String wxOpenid = json0bject.getStr("wxOpenid");
            frontUserModel.setWxOpenid(wxOpenid);
            return CommonResult.ok(frontUserService.updatePassword(frontUserModel));
        }
    }
    /**
     * @Author XMY
     * @Description 根据id用户信息
     * @Date 2023/12/12 8:28
     * @Return
     */
    @GetMapping("/getFrontUserById")
    @ApiOperation(value = "根据id用户信息")
    public CommonResult getFrontUserById(@RequestParam("token") String token) throws CommonException {
        String jsonstr = stringRedisTemplate.opsForValue().get(token);
        if (jsonstr == null || jsonstr.equals("")) {
            return CommonResult.error(404,"用户信息失效,请重新登录");
        } else {
            // 使用JSONObject解析ISON字符串
            JSONObject json0bject = new JSONObject(jsonstr);
            // 获取id字段的值
            int userId = json0bject.getInt("id");
            return CommonResult.ok(frontUserService.getFrontUserById(userId));
        }
    }

    /**
     * @param file
     * @Author XMY
     * @Description 前端头像上传
     * @Date 2023/12/11 11:02
     * @Return
     */
    @PostMapping("/headPortraitUpload")
    @ApiOperation(value = "前端头像上传接口")
    public CommonResult headPortraitUpload(@RequestParam MultipartFile file) throws CommonException {
        return CommonResult.ok(frontUserService.headPortraitUpload(file));
    }

    /**
     * @Author XMY
     * @Description 根据用户id获取个性标签
     * @Date 2023/12/12 14:27
     * @Return
     */
    @GetMapping("/getTagListByUserId")
    @ApiOperation(value = "用户个性标签")
    public CommonResult getTagListByUserId(@RequestParam("token") String token) {
        String jsonstr = stringRedisTemplate.opsForValue().get(token);
        if (jsonstr == null || jsonstr.equals("")) {
            return CommonResult.error(404,"用户信息失效,请重新登录");
        } else {
            // 使用JSONObject解析ISON字符串
            JSONObject json0bject = new JSONObject(jsonstr);
            // 获取id字段的值
            int userId = json0bject.getInt("id");
            return CommonResult.ok(frontUserService.getTagListByUserId(userId));
        }
    }

    /**
     * @Author LYX
     * @Description 用户添加个性标签
     * @Date 2024/3/5 19:27
     * @Return
     */
    @PostMapping("/insertTag")
    @ApiOperation(value = "添加个性标签")
    public CommonResult insertTag(@RequestParam String tagName, String token) throws CommonException {
        String jsonstr = stringRedisTemplate.opsForValue().get(token);
        if (jsonstr == null || jsonstr.equals("")) {
            return CommonResult.error(404,"用户信息失效,请重新登录");
        } else {
            // 使用JSONObject解析ISON字符串
            JSONObject json0bject = new JSONObject(jsonstr);
            // 获取id字段的值
            int userId = json0bject.getInt("id");
            FrontUser frontUser = frontUserService.getFrontUserByUserId(userId);
            Tag tag=new Tag();
            tag.setTagName(tagName);
            frontUserService.insertTag(tag);
            Integer newId = tag.getId();
            int userid = frontUser.getId();
            boolean jg = frontUserService.insertUserTag(userid, newId);
            if (jg) {
                return CommonResult.ok("添加标签成功");
            } else {
                return CommonResult.ok("添加标签失败");
            }
        }
    }

//    Web
    /**
     * @Author XMY
     * @Description 前台用户管理
     * @Date 2023/12/14 14:46
     * @Return
     * @param frontUser
     * @param pageRequest
     */
    @GetMapping("/getFrontUserList")
    @ApiOperation(value = "前台用户管理")
    public CommonResult getFrontUserList(FrontUser frontUser, PageRequest pageRequest){
        return CommonResult.ok(frontUserService.getFrontUserList(frontUser, pageRequest));
    }

    /**
     * @Author XMY
     * @Description 新增用户
     * @Date 2023/12/14 20:27
     * @Return
     * @param frontUserModel
     */
    @PostMapping("/addFrontUser")
    @ApiOperation(value = "添加用户de方法")
    public CommonResult addFrontUser(@RequestBody FrontUserModel frontUserModel) throws CommonException {
        return CommonResult.ok(frontUserService.addFrontUser(frontUserModel));
    }

    /**
     * @Author XMY
     * @Description 添加/修改用户信息邮箱校验
     * @Date 2023/12/15 13:37
     * @Return
     * @param email
     */
    @GetMapping("/verifyEmail/{email}")
    @ApiOperation(value = "校验邮箱")
    public CommonResult verifyEmail(@PathVariable String email){
        return CommonResult.ok(frontUserService.verifyEmail(email));
    }

    /**
     * @Author XMY
     * @Description 修改用户信息
     * @Date 2023/12/14 19:41
     * @Return
     * @param frontUserModel
     */
    @PutMapping("updateFrontUserById")
    @ApiOperation(value = "修改前端用户信息")
    public CommonResult updateFrontUserById(@RequestBody FrontUserModel frontUserModel)throws CommonException{
        return CommonResult.ok(frontUserService.updateFrontUserById(frontUserModel));
    }
    /**
     * @Author XMY
     * @Description 删除用户信息
     * @Date 2023/12/6 19:43
     * @Return
     * @param userId
     */
    @DeleteMapping("/delFrontUserById/{userId}")
    @OptLog(modular = "用户管理", type = CommonConstants.DELETE, describe = "删除用户信息")
    @ApiOperation(value = "删除用户信息方法")
    public CommonResult delFrontUserById(@PathVariable Integer[] userId) throws CommonException {
        return frontUserService.delFrontUserById(userId);
    }

    /**
     * @Author XMY
     * @Description 导出接口
     * @Date 2023/12/15 10:47
     * @Return
     * @param response
     */
    @PostMapping("/export")
    @ApiOperation(value ="导出接口")
    public void export(HttpServletResponse response) throws Exception {
        frontUserService.export(response);
    }
    /**
     * @Author XMY
     * @Description 导入接口
     * @Date 2023/12/26 10:20
     * @Return
     * @param file
     */
    @PostMapping("/importData")
    @ApiOperation(value ="导入接口")
    public Boolean importData(MultipartFile file) throws Exception{
        return frontUserService.importData(file);
    }
}